-- ============================================
-- SHOOT LE ZENH - ComputerCraft / CC:Tweaked
-- Nécessite : Advanced Computer + Advanced Monitor (couleur)
-- ============================================

local MISE = 1
local points = 100

local ROUND_DURATION = 15   -- secondes
local TICK = 0.12           -- intervalle d'animation
local DUCK_W, DUCK_H = 3, 2
local NUM_DUCKS = 2         -- canards presents en meme temps

local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
local prevTerm = term.redirect(mon)
local w, h = term.getSize()

local playTop, playBottom = 5, h - 2
local playLeft, playRight = 1, w

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === CANARDS ===
local function randomSpeed(level)
    local mag = math.random(1, level)
    if math.random(2) == 1 then mag = -mag end
    return mag
end

local function spawnDuck(speedLevel)
    return {
        x = math.random(playLeft, math.max(playLeft, playRight - DUCK_W)),
        y = math.random(playTop, math.max(playTop, playBottom - DUCK_H)),
        dx = randomSpeed(speedLevel),
        dy = randomSpeed(speedLevel),
    }
end

local function ensureNonZero(d)
    if d.dx == 0 then d.dx = 1 end
    if d.dy == 0 then d.dy = 1 end
end

local function drawDuck(duck)
    -- petit visage blanc avec 2 yeux = le "zenh"
    fillArea(duck.x, duck.y, duck.x + DUCK_W - 1, duck.y + DUCK_H - 1, colors.white)
    term.setTextColor(colors.black)
    term.setBackgroundColor(colors.white)
    term.setCursorPos(duck.x, duck.y)
    term.write("o o") -- les 2 yeux, sur la ligne du haut
end

local function eraseDuck(duck)
    fillArea(duck.x, duck.y, duck.x + DUCK_W - 1, duck.y + DUCK_H - 1, colors.black)
end

local function moveDuck(duck)
    duck.x = duck.x + duck.dx
    duck.y = duck.y + duck.dy

    if duck.x < playLeft then
        duck.x = playLeft
        duck.dx = -duck.dx
    elseif duck.x + DUCK_W - 1 > playRight then
        duck.x = playRight - DUCK_W + 1
        duck.dx = -duck.dx
    end

    if duck.y < playTop then
        duck.y = playTop
        duck.dy = -duck.dy
    elseif duck.y + DUCK_H - 1 > playBottom then
        duck.y = playBottom - DUCK_H + 1
        duck.dy = -duck.dy
    end
end

local function touchHitsDuck(duck, x, y)
    return x >= duck.x and x <= duck.x + DUCK_W - 1 and y >= duck.y and y <= duck.y + DUCK_H - 1
end

-- === CADRE ===
local function drawHeader(timeLeft, hits)
    term.setBackgroundColor(colors.black)
    fillArea(1, 1, w, playTop - 1, colors.black)
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "SHOOT LE ZENH", colors.white)
    centerText(3, "Points : " .. points .. "   Temps : " .. timeLeft .. "s   Touches : " .. hits, colors.lime)
end

local function payoutFor(hits)
    if hits >= 13 then return MISE * 8
    elseif hits >= 8 then return MISE * 4
    elseif hits >= 4 then return MISE * 2
    else return 0 end
end

-- === UNE MANCHE ===
local function playRound()
    if points < MISE then
        drawHeader(0, 0)
        centerText(math.floor(h / 2), "PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return
    end
    points = points - MISE

    fillArea(playLeft, playTop, playRight, playBottom, colors.black)

    local speedLevel = 1
    local hits = 0
    local ducks = {}
    for i = 1, NUM_DUCKS do
        local d = spawnDuck(speedLevel)
        ensureNonZero(d)
        ducks[i] = d
        drawDuck(d)
    end

    local elapsed = 0
    drawHeader(ROUND_DURATION, hits)
    local timerId = os.startTimer(TICK)

    while elapsed < ROUND_DURATION do
        local event, p1, p2, p3 = os.pullEvent()

        if event == "timer" and p1 == timerId then
            elapsed = elapsed + TICK
            if elapsed >= 5 and speedLevel == 1 then speedLevel = 2 end
            if elapsed >= 10 and speedLevel == 2 then speedLevel = 3 end

            for _, d in ipairs(ducks) do
                eraseDuck(d)
                moveDuck(d)
                drawDuck(d)
            end
            drawHeader(math.max(0, math.floor(ROUND_DURATION - elapsed)), hits)
            timerId = os.startTimer(TICK)

        elseif event == "monitor_touch" then
            local tx, ty = p2, p3
            for i, d in ipairs(ducks) do
                if touchHitsDuck(d, tx, ty) then
                    hits = hits + 1
                    eraseDuck(d)
                    local newDuck = spawnDuck(speedLevel)
                    ensureNonZero(newDuck)
                    ducks[i] = newDuck
                    drawDuck(newDuck)
                    drawHeader(math.max(0, math.floor(ROUND_DURATION - elapsed)), hits)
                    break
                end
            end
        end
    end

    for _, d in ipairs(ducks) do eraseDuck(d) end

    local gain = payoutFor(hits)
    points = points + gain

    local msg, msgColor
    if gain == 0 then
        msg, msgColor = hits .. " touches - Perdu, reessaie !", colors.red
    else
        msg, msgColor = hits .. " touches - Tu gagnes +" .. gain .. " !", colors.lime
    end

    drawHeader(0, hits)
    centerText(math.floor((playTop + playBottom) / 2), msg, msgColor)
    sleep(2.5)
end

-- === ECRAN D'ACCUEIL ===
local button = {}

local function drawIdle()
    term.setBackgroundColor(colors.black)
    term.clear()
    centerText(1, "=== CASINO COMPUTERCRAFT ===", colors.yellow)
    centerText(2, "SHOOT LE ZENH", colors.white)
    centerText(3, "Points : " .. points, colors.lime)
    centerText(5, "4+ touches : x2   8+ : x4   13+ : x8", colors.lightGray)

    local label = "MISER (" .. MISE .. " point) ET TIRER"
    local bw = #label + 4
    local x1 = math.floor((w - bw) / 2) + 1
    local y = math.floor(h / 2)
    term.setBackgroundColor(colors.green)
    term.setTextColor(colors.white)
    for x = x1, x1 + bw - 1 do
        term.setCursorPos(x, y)
        term.write(" ")
    end
    term.setCursorPos(x1 + 2, y)
    term.write(label)
    button = { x1 = x1, x2 = x1 + bw - 1, y = y }
end

-- === PROGRAMME PRINCIPAL ===
drawIdle()

while true do
    local event, side, x, y = os.pullEvent("monitor_touch")
    if x >= button.x1 and x <= button.x2 and y == button.y then
        playRound()
        drawIdle()
    end
end